package sm.upgrade.util;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import sm.upgrade.api.DataUpgradeInterceptor;
import sm.util.Util;

public class DataUpgradePolicy {

	private Set<String> ignoreFields = new HashSet<String>();

	private Map<String, List<Object>> baseIdentifiers = new HashMap<String, List<Object>>();

	private DataUpgradeInterceptor defaultInterceptor;

	private Map<String, DataUpgradeInterceptor> interceptors = new HashMap<String, DataUpgradeInterceptor>();

	public void setDefaultInterceptor(DataUpgradeInterceptor defaultInterceptor) {
		this.defaultInterceptor = defaultInterceptor;
	}

	public void setInterceptors(Map<String, DataUpgradeInterceptor> interceptors) {
		this.interceptors = interceptors;
	}

	public void setBaseIdentifiers(List<String> identifiers) {
		for (String identifer : identifiers) {
			int fileIdx = identifer.indexOf(",");
			if (fileIdx != -1) {
				String file = identifer.substring(0, fileIdx);
				String keyPath = identifer.substring(fileIdx + 1);
				Object[] keyPaths = Util.parseKey(keyPath);
				this.baseIdentifiers.put(file, Arrays.asList(keyPaths));
			}
		}

	}

	public void setIgnoreFields(Set<String> ignoreFields) {
		this.ignoreFields = ignoreFields;
	}

	public Set<String> getIgnoreFields() {
		return ignoreFields;
	}

	public Set<String> getIgnoreFields(String fileName) {
		Set<String> fileIgnoreFields = new HashSet<String>();
		for (String ignoreField : ignoreFields) {
			int fileIdx = ignoreField.indexOf(",");
			if (fileIdx == -1) {
				fileIgnoreFields.add(ignoreField);
			} else {
				String file = ignoreField.substring(0, fileIdx);
				if (fileName.equals(file)) {
					String field = ignoreField.substring(fileIdx + 1);
					fileIgnoreFields.add(field);
				}

			}
		}
		return fileIgnoreFields;
	}

	public String[] getBaseIdentifier(String fileName) {
		String[] ids = null;
		List<Object> identifer = baseIdentifiers.get(fileName);
		if (identifer != null) {
			ids = identifer.toArray(new String[0]);
		}
		return ids;
	}

	public DataUpgradeInterceptor getInterceptor(String fileName) {
		DataUpgradeInterceptor interceptor = interceptors.get(fileName);
		if (interceptor == null) {
			interceptor = defaultInterceptor;
		}
		return interceptor;
	}
}
